import json

from .to_database import build_vue_json_for_entry,sync_vue_json_to_db

def handle_entry(data):
    # 模拟业务逻辑处理，返回接收到的数据
    return {
        "status": "success",
        "received_data": data
    }

def sync_from_backend(data):
    entry_id = data.get("entry_id")[0]
    entry_dict = build_vue_json_for_entry(entry_id)
    if entry_dict is not None:
        return {
            "status": "success",
            "data": entry_dict
        }
    return {
        "status": "error",
        "message": "Entry not found"
    }

def sync_to_backend(data):
    print(data)
    if sync_vue_json_to_db(data.get("entry_id"), data.get("tags")):
        return {
            "status": "success",
            "message": "Data synced successfully"
        }
    # else
    return {
        "status": "error",
        "message": "Invalid entry ID"
    }

from .to_database import get_previous_entry_id,get_next_entry_id

def previous_entry(data):
    print(data)
    entry_id = data.get("entry_id")[0]
    previous_id = get_previous_entry_id(entry_id)
    if previous_id:
        return {
            "status": "success",
            "entry_id_new": previous_id
        }
    return {
        "status": "error",
        "message": "No previous entry"
    }

def next_entry(data):
    entry_id = data.get("entry_id")[0]
    next_id = get_next_entry_id(entry_id)
    if next_id:
        return {
            "status": "success",
            "entry_id_new": next_id
        }
    return {
        "status": "error",
        "message": "No next entry"
    }

# 注册路由和处理函数的映射
api_routes = {
    "/api/entry": handle_entry,
    "/api/syncfrom": sync_from_backend,
    "/api/syncto": sync_to_backend,
    "/api/nxtid": next_entry,
    "/api/preid": previous_entry
}


# ## 新路由的注册

# def handle_another_endpoint(data):
#     return {
#         "status": "success",
#         "message": "Handling another endpoint",
#         "received_data": data
#     }

# api_routes["/api/another"] = handle_another_endpoint
